package com.toocms.jinjuhang.dialog.promote_business_card

import android.graphics.Bitmap
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.media.MediaScannerConnection
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore
import android.view.*
import android.widget.ImageView
import android.widget.TextView
import androidx.cardview.widget.CardView
import androidx.constraintlayout.widget.Group
import androidx.fragment.app.DialogFragment
import com.blankj.utilcode.util.ImageUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.StringUtils
import com.toocms.jinjuhang.R
import com.toocms.jinjuhang.config.Urls
import com.toocms.jinjuhang.config.UserRepository
import com.toocms.jinjuhang.data.center.GetCodeData
import com.toocms.jinjuhang.widget.view_model.requestData
import com.toocms.jinjuhang.widget.view_model.showToast
import com.toocms.tab.imageload.ImageLoader
import java.io.File

class PromoteBusinessCardDialog : DialogFragment() {

    var posterCl: CardView? = null
    var nickname0Tv: TextView? = null
    var nicknameTv: TextView? = null
    var coverIv: ImageView? = null
    var qrCode0Iv: ImageView? = null
    var qrCode1Iv: ImageView? = null
    var qrCode2Iv: ImageView? = null
    var closeIv: ImageView? = null
    var saveToAlbumTv: TextView? = null
    var qrCodeStyle0Group: Group? = null
    var qrCodeStyle1Group: Group? = null

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.dialog_promote_business_card, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        view.apply {
            nickname0Tv = findViewById(R.id.nickname0_tv)
            nicknameTv = findViewById(R.id.nickname_tv)
            posterCl = findViewById(R.id.poster_cl)
            coverIv = findViewById(R.id.cover_iv)
            qrCodeStyle0Group = findViewById(R.id.qr_code_style0_group)
            qrCodeStyle1Group = findViewById(R.id.qr_code_style1_group)
            qrCode0Iv = findViewById(R.id.qr_code0_iv)
            qrCode1Iv = findViewById(R.id.qr_code1_iv)
            qrCode2Iv = findViewById(R.id.qr_code2_iv)
            closeIv = findViewById(R.id.close_iv)
            saveToAlbumTv = findViewById(R.id.save_to_album_tv)
            closeIv?.setOnClickListener { dismiss() }
            saveToAlbumTv?.setOnClickListener {
                val qrBitmap = ImageUtils.view2Bitmap(posterCl)
                var saveImagePath =
                    "${requireContext().getExternalFilesDir(Environment.DIRECTORY_PICTURES)?.path}${File.pathSeparator}qr${System.currentTimeMillis()}.png"
                ImageUtils.save(qrBitmap, saveImagePath, Bitmap.CompressFormat.PNG, 100)
                MediaStore.Images.Media.insertImage(
                    requireContext().contentResolver,
                    saveImagePath,
                    File(saveImagePath).name,
                    null
                )
                MediaScannerConnection.scanFile(
                    requireContext(),
                    arrayOf(saveImagePath),
                    null,
                    null
                )
                this@PromoteBusinessCardDialog.showToast(StringUtils.getString(R.string.str_save_succeed))
            }
            nickname0Tv?.text = UserRepository.user.real_name
            nicknameTv?.text = UserRepository.user.real_name
            LogUtils.e(UserRepository.user.real_name)
        }
        getCode()
    }

    override fun onStart() {
        super.onStart()
        config()
    }

    private fun displayMetrics() = resources.displayMetrics

    private fun config() {
        dialog?.run {
            setCancelable(true)
            setCanceledOnTouchOutside(true)
            window
        }?.apply {
            setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
            setGravity(Gravity.CENTER)
            setLayout(
                (displayMetrics().widthPixels.toFloat() * 0.75f).toInt(),
                WindowManager.LayoutParams.WRAP_CONTENT
            )
        }
    }

    private fun getCode() {
        val params = mutableMapOf<String, String?>()
        params["member_id"] = UserRepository.user.member_id
        requestData(Urls.Center.GET_CODE, params, GetCodeData::class.java, { data ->
            ImageLoader.loadUrl2Image(data.background, coverIv, R.mipmap.img_default)
            if (!data.url.isNullOrEmpty() && !data.h5_url.isNullOrEmpty()) {
                ImageLoader.loadUrl2Image(data.h5_url, qrCode1Iv, R.mipmap.img_default)
                ImageLoader.loadUrl2Image(data.url, qrCode2Iv, R.mipmap.img_default)
                qrCodeStyle0Group?.visibility = View.GONE
                qrCodeStyle1Group?.visibility = View.VISIBLE
            } else {
                ImageLoader.loadUrl2Image(
                    if (data.h5_url.isNullOrEmpty()) data.url else data.h5_url,
                    qrCode0Iv,
                    R.mipmap.img_default
                )
                qrCodeStyle0Group?.visibility = View.VISIBLE
                qrCodeStyle1Group?.visibility = View.GONE
            }
        })
    }

}